package edu.msg.jthr.web.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.msg.jthr.backend.model.Candidate;
import edu.msg.jthr.backend.model.Job;
import edu.msg.jthr.backend.model.RecommendedCandidate;
import edu.msg.jthr.backend.model.User;
import edu.msg.jthr.backend.service.CandidateService;
import edu.msg.jthr.backend.service.JobService;
import edu.msg.jthr.backend.service.UserService;
import edu.msg.jthr.web.util.RoleAssembler;

/**
 * @author Elod
 */
@WebServlet("/RecommendCandidate")
public class RecommendCandidate extends HttpServlet {
	// TODO fixe this
	private static final long serialVersionUID = 1L;
	@EJB
	private CandidateService candidateService;
	@EJB
	private JobService jobService;
	@EJB
	private UserService userService;
	private HttpSession session;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RecommendCandidate() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		User user = (User) session.getAttribute("activeUser");
		if (user == null) {
			user = userService.getUserByUserName(request.getUserPrincipal()
					.toString());
			String role = RoleAssembler.getRole(user.getUserGroups());
			session.setAttribute("role", role);
			session.setAttribute("activeUser", user);
		}
		request.getRequestDispatcher("/pages/RecommendCandidate.jsp").forward(
				request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response) Recommend actual candidate to the job in back
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		session = request.getSession(true);
		Candidate candidate = candidateService.getById(Long.parseLong(request
				.getParameter("candidateId")));
		Job job = (Job) session.getAttribute("job");
		RecommendedCandidate rc = new RecommendedCandidate(job, candidate);
		job.getRecomendedCandidates().add(rc);
		jobService.update(job);

		doGet(request, response);
	}

}
